const express = require('express');
const  router = express.Router();
const util = require('utility')

// 添加管理员
router.post('/register' ,async (req,res)=>{
  const { Admin }  = req.Model;
  let {
    userName ,   // 管理员用户名
    pwd,   // 管理员密码
    time,
  }  = req.body;
  // 数据过滤的操作 
  let admin = await Admin.findOne({userName}) 
  if(admin) {
    return  res.send({code:500,info:'用户名已存在!'})
  }else {
    try {
      await Admin.create({
        userName,
        pwd:util.md5(pwd), // 使用md5加密用户传进来的明文的密码
        time
      })
      res.send({code:200,info:'注册成功'})
    } catch(e) {
      res.send({code:500,info:'注册失败'})
    }
  }
})

router.post('/edit' ,async (req,res)=>{
  const { Admin }  = req.Model;

     // 数据过滤的操作 
    const { adminid , pwd, ...updateData} = req.body;
   try {
      await Admin.findByIdAndUpdate(adminid,{
        ...updateData,
        pwd:util.md5(pwd)
      });
      res.send({code:200,info:'修改成功'})
   } catch(e) {
      res.send({code:500,info:'修改失败'})
   }
})

// 分页查询
router.post('/getAll', async (req,res)=>{
        const { Admin} = req.Model;
        let { page=1,limit=10} = req.body;
        const skip =  (page - 1 ) * limit; // 查询的起点（偏移量）
          // 初始化 查询条件      
        try {
          let admins = await Admin.find({},{},{skip,limit}) // 分页查询
          let count = await Admin.count(where) // 获取符合条件的总数
          res.send({code:200,info:'查询成功',data:admins,count}); 
        }catch(e){
          res.send({code:500,info:'获取失败'})
        }
})

// 查询单个管理元信息

router.post('/getOne', async (req,res)=>{
  const { Admin} = req.Model;
  let { adminid } = req.body;
  if(!adminid) return res.send({code:500,info:'请传入一个正确的id'})

  try {
    let admin = await Admin.findById(adminid) // 分页查询
    res.send({code:200,info:'查询成功',data:admin});
  }catch(e){
    res.send({code:500,info:'获取失败'})
  }
})

router.post('/del', async (req,res)=>{
  const { Admin} = req.Model;
  let { adminid } = req.body;

  if(!adminid) return res.send({code:500,info:'请传入一个正确的id'})

  try {
    let admin = await Admin.findByIdAndRemove(adminid) // 分页查询
    res.send({code:200,info:'删除成功',data:admin});
  }catch(e){

    res.send({code:500,info:'删除失败'})
  }
})
router.post('/login', async (req,res)=>{
  const { Admin} = req.Model;
  let { userName,pwd } = req.body;
  // console.log('req.headers',req.headers)
  try {
    let admin = await Admin.findOne({userName}) 
    if(!admin) return  res.send({code:500,info:'用户名或者密码错误'})
    const md5pwd = util.md5(pwd)
    if(admin.pwd !== md5pwd)  return  res.send({code:500,info:'用户名或者密码错误'})

    res.send({code:200,info:'登录成功',data:{
       id: admin._id,
       userName:admin.userName,
       loginFlag: true,
    }});
    
  }catch(e){
    res.send({code:500,info:'登录失败'})
  }
})

module.exports = router;